import sys
import os
import logging
import re
import json
from typing import Dict, List, Any, Optional, Tuple

# 添加项目根路径到 sys.path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))

# 导入 MySQLUtil
from shared.utils.MySQLUtil import MySQLUtil

# 设置日志
logger = logging.getLogger(__name__)

def get_毕业生培养目标了解情况分布_表格里含选项分布_了解度_均值_(
    project_id: int,
    questionnaire_ids: List[int],
    product_code: Optional[str] = None,
    project_code: Optional[str] = None,
    region_code: Optional[str] = None
) -> Dict[str, Any]:
    """
    毕业生培养目标了解情况分布（表格里含选项分布、了解度、均值） - 指标计算函数
    
    ## 指标说明
    该指标用于统计毕业生对所学专业培养目标的了解情况，包括：
    1. 各选项（很了解、了解较多、基本了解、了解较少、很不了解）的分布比例
    2. 前三项（很了解、了解较多、基本了解）的合计占比（了解度）
    3. 各选项的加权平均值（5分制）
    指标按院系分组展示
    
    ## Args
        project_id (int): 项目ID，用于查询项目配置信息
        questionnaire_ids (List[int]): 问卷ID集合，用于确定数据范围
        product_code (Optional[str]): 产品编码，用于路由到特定计算逻辑
        project_code (Optional[str]): 项目编码，用于路由到特定计算逻辑
        region_code (Optional[str]): 区域编码，用于路由到特定计算逻辑
        
    ## 示例
    ### 输入
    ```json
    {
        "project_id": 6768,
        "questionnaire_ids": [12709, 12710]
    }
    ```
    
    ### 输出
    ```json
    {
        "success": true,
        "message": "ok", 
        "code": 0,
        "result": [
            {
                "college": "计算机学院",
                "option_distribution": {
                    "很了解": 0.25,
                    "了解较多": 0.35,
                    "基本了解": 0.20,
                    "了解较少": 0.15,
                    "很不了解": 0.05
                },
                "understanding_degree": 0.80,
                "average_score": 3.75
            }
        ]
    }
    ```
    """
    logger.info(f"开始计算指标: 毕业生培养目标了解情况分布（表格里含选项分布、了解度、均值）, 项目ID: {project_id}")
    
    try:
        db = MySQLUtil()  

        # 1. 查询项目配置信息
        project_sql = """
        SELECT client_code, item_year, dy_target_items, split_tb_paper 
        FROM client_item 
        WHERE id = %s
        """
        project_info = db.fetchone(project_sql, (project_id,))
        if not project_info:
            raise ValueError(f"未找到项目ID={project_id}的配置信息")

        client_code = project_info['client_code']
        item_year = project_info['item_year']
        split_tb_paper = project_info['split_tb_paper']
        
        logger.info(f"项目配置: client_code={client_code}, item_year={item_year}, split_tb_paper={split_tb_paper}")

        # 2. 计算 shard_tb_key
        shard_tb_key = re.sub(r'^[A-Za-z]*0*', '', client_code)
        logger.info(f"计算得到 shard_tb_key: {shard_tb_key}")

        # 3. 查询问卷信息
        questionnaire_sql = f"""
        SELECT id, dy_target 
        FROM wt_template_customer 
        WHERE id IN ({','.join(['%s'] * len(questionnaire_ids))})
        """
        questionnaires = db.fetchall(questionnaire_sql, tuple(questionnaire_ids))
        if not questionnaires:
            raise ValueError(f"未找到问卷ID集合={questionnaire_ids}的配置信息")
        
        logger.info(f"查询到问卷信息: {questionnaires}")

        # 4. 过滤特定调研对象的问卷
        valid_questionnaire_ids = [q['id'] for q in questionnaires if q['dy_target'] == 'GRADUATE_SHORT']
        if not valid_questionnaire_ids:
            raise ValueError("未找到目标调研对象的问卷ID")
            
        logger.info(f"找到有效问卷ID: {valid_questionnaire_ids}")

        # 5. 查询问题信息
        question_sql = """
        SELECT id, wt_code, wt_obj 
        FROM wt_template_question_customer 
        WHERE cd_template_id = %s AND wt_code = %s AND is_del = 0
        """
        question_info = db.fetchone(question_sql, (valid_questionnaire_ids[0], 'T00003303'))
        if not question_info:
            raise ValueError("未找到指定问题编码的问题信息")
            
        logger.info(f"找到问题信息: {question_info['id']}")

        # 6. 解析问题选项
        wt_obj = json.loads(question_info['wt_obj'])
        options = []
        for item in wt_obj['itemList']:
            options.append({
                'key': item['key'],
                'val': item['val'],
                'weight': item.get('weight', 1)
            })
        logger.info(f"解析到问题选项: {options}")

        # 7. 构建动态表名
        answer_table = f"re_dy_paper_answer_{split_tb_paper}"
        student_table = f"dim_client_target_baseinfo_student_{item_year}"

        # 8.1 计算各选项占比
        ratio_sql = f"""
        SELECT
            college AS gwd1,
            sum(c1)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) AS ratio_c1,
            sum(c2)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) AS ratio_c2,
            sum(c3)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) AS ratio_c3,
            sum(c4)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) AS ratio_c4,
            sum(c5)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) AS ratio_c5
        FROM
            {answer_table} t1
            JOIN {student_table} s ON t1.target_no = s.target_no
        WHERE
            t1.cd_template_id = %s
            AND t1.wid = %s
            AND t1.ans_true = 1
            AND s.shard_tb_key = %s
            AND s.item_year = %s
            AND college != ''
        GROUP BY
            college
        """
        ratio_results = db.fetchall(ratio_sql, (valid_questionnaire_ids[0], question_info['id'], shard_tb_key, item_year))
        
        # 8.2 计算了解度(前三项占比)
        understanding_sql = f"""
        SELECT
            college AS gwd1,
            (sum(c1)+sum(c2)+sum(c3))/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) AS ratio
        FROM
            {answer_table} t1
            JOIN {student_table} s ON t1.target_no = s.target_no
        WHERE
            t1.cd_template_id = %s
            AND t1.wid = %s
            AND t1.ans_true = 1
            AND s.shard_tb_key = %s
            AND s.item_year = %s
            AND college != ''
        GROUP BY
            college
        """
        understanding_results = db.fetchall(understanding_sql, (valid_questionnaire_ids[0], question_info['id'], shard_tb_key, item_year))
        
        # 8.3 计算均值(加权平均分)
        average_sql = f"""
        SELECT
            college AS gwd1,
            (sum(c1)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) * 5 +
            sum(c2)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) * 4 +
            sum(c3)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) * 3 +
            sum(c4)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) * 2 +
            sum(c5)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) * 1) AS average_score
        FROM
            {answer_table} t1
            JOIN {student_table} s ON t1.target_no = s.target_no
        WHERE
            t1.cd_template_id = %s
            AND t1.wid = %s
            AND t1.ans_true = 1
            AND s.shard_tb_key = %s
            AND s.item_year = %s
            AND college != ''
        GROUP BY
            college
        """
        average_results = db.fetchall(average_sql, (valid_questionnaire_ids[0], question_info['id'], shard_tb_key, item_year))

        # 9. 合并结果
        result_map = {}
        for row in ratio_results:
            college = row['gwd1']
            result_map[college] = {
                'college': college,
                'option_distribution': {
                    '很了解': float(row['ratio_c1']),
                    '了解较多': float(row['ratio_c2']),
                    '基本了解': float(row['ratio_c3']),
                    '了解较少': float(row['ratio_c4']),
                    '很不了解': float(row['ratio_c5'])
                }
            }
        
        for row in understanding_results:
            college = row['gwd1']
            if college in result_map:
                result_map[college]['understanding_degree'] = float(row['ratio'])
        
        for row in average_results:
            college = row['gwd1']
            if college in result_map:
                result_map[college]['average_score'] = float(row['average_score'])

        final_result = list(result_map.values())

        logger.info(f"指标 '毕业生培养目标了解情况分布（表格里含选项分布、了解度、均值）' 计算成功")
        return {
            "success": True,
            "message": "ok",
            "code": 0,
            "result": final_result
        }

    except Exception as e:
        logger.error(f"计算指标 '毕业生培养目标了解情况分布（表格里含选项分布、了解度、均值）' 时发生错误: {str(e)}", exc_info=True)
        return {
            "success": False,
            "message": f"数据获取失败: 毕业生培养目标了解情况分布（表格里含选项分布、了解度、均值）",
            "code": 500,
            "error": str(e)
        }